<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline>
      <!-- <el-form-item>
        <el-select v-model="versionCode" placeholder="选择版本">
          <el-option v-for="dict in versionList" :key="dict.versionCode" :label="`${dict.versionCode}（${dict.versionName}）`" :value="dict.versionCode" />
        </el-select>
      </el-form-item> -->
      <el-form-item prop="deptId1">
        <treeselect v-model="queryParams.deptId1" class="tree-select-custom" placeholder="请选择所属部门" no-results-text="暂无数据匹配" no-options-text="暂无数据" :normalizer="normalizerDept" :options="deptOptions" @select="selectDept" />
      </el-form-item>
      <el-form-item prop="projectName">
        <el-input v-model.trim="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item prop="rdcType" v-if="rdcTypeList.length >= 2">
        <el-select v-model="queryParams.rdcType" placeholder="检查单位" clearable style="width: 100px">
          <el-option v-for="dict in rdcTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="isLockout">
        <el-select v-model="queryParams.isLockout" placeholder="锁定状态" clearable style="width: 100px">
          <el-option v-for="dict in lockStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="-" start-placeholder="检查开始日期" end-placeholder="检查结束日期" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" :disabled="disableAction" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" :disabled="disableAction" @click="resetQuery">重置</el-button>
        <el-button size="mini" type="primary" icon="el-icon-plus" v-if="showBtns.add" :disabled="disableAction" @click="openEditItem()">新增</el-button>
        <el-button icon="el-icon-download" :disabled="disableAction" :loading="exportLoading" @click="handleExport" v-if="showBtns.isExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table class="table" v-loading="cfgLoading || listLoading" :data="list" size="small">
      <el-table-column label="所属部门" prop="showDeptName" width="250" />
      <el-table-column label="项目" prop="projectName" width="150" />
      <el-table-column label="标段" prop="section" width="80" />
      <el-table-column label="项目(检查口径)" prop="inpectionCaliber" width="110" />
      <el-table-column label="施工单位" prop="constructionName" width="200" />
      <el-table-column label="检查单位" align="center" width="80" key="rdcType" v-if="hasRdcType">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_rdc_type" :value="row.rdcType" />
      </el-table-column>
      <el-table-column label="检查得分" min-width="300">
        <template slot-scope="{ row }">
          <ScoreDisplay :value="row" :cfg="cfgInfo" style="zoom: 0.9" />
        </template>
      </el-table-column>
      <el-table-column label="检查人员" align="center" width="100" prop="principalUserName" />
      <el-table-column label="检查日期" align="center" prop="checkDate" width="100" />
      <el-table-column label="锁定状态" align="center" width="70" fixed="right">
        <div slot-scope="{ row }">
          <div @click="toggleLock(row)" style="display: inline-block; cursor: pointer" v-if="row.isEditLock">
            <i class="el-icon-loading" v-if="!!row.lockLoading" />
            <el-switch class="g-switch-in" v-model="row.isLockout" :active-value="1" :inactive-value="0" active-text="锁定" inactive-text="未锁" :width="50" style="pointer-events: none" v-else />
          </div>
          <el-tag size="small" :type="row.isLockout ? 'primary' : 'info'" v-else>{{ row.isLockout ? '锁定' : '未锁' }}</el-tag>
        </div>
      </el-table-column>
      <el-table-column label="操作" align="center" width="170" fixed="right">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openEditItem(row)" v-if="!row.isLockout && showBtns.edit">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="handleDelete(row)" v-if="!row.isLockout && showBtns.remove">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="openDetail(row)" v-if="showBtns.info">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <EditItem ref="EditItem" v-model="showEditItem" @ok="getList" />
    <ChkitemScoreDetail ref="ChkitemScoreDetail">
      <template v-slot:baseInfo="{ info }">
        <el-descriptions-item label="陪检专家" v-if="info.expertName">{{ info.expertName }}</el-descriptions-item>
      </template>
    </ChkitemScoreDetail>
  </div>
</template>
<script>
// 土建过程
import auth from '@/plugins/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { CQ_EVAL_DATA_TYPE as DATA_TYPE, lockStatusList } from '@/utils/baseData'
import { treeselect } from '@/api/system/dept'
import { listVersion, listChkitem, pageScorePrjchk, deletePrjchk, enableTaskPrjchk, disableTaskPrjchk, exportReportPrjchk } from '@/api/checkScore/cqEval'
import EditItem from './EditCivil'
import ScoreDisplay from '@/views/checkScore/chkitemScore/ScoreDisplay'
import ChkitemScoreDetail from '@/views/checkScore/chkitemScore/ChkitemScoreDetail'

export default {
  components: { Treeselect, EditItem, ScoreDisplay, ChkitemScoreDetail },
  dicts: ['cq_eval_rdc_type'],
  data() {
    return {
      lockStatusList,
      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId1: undefined,
        projectName: '',
        rdcType: '',
        isLockout: ''
      },
      dateRange: [],
      deptOptions: [],
      hasRdcType: false,
      exportLoading: false,
      showEditItem: false,
      chkitemCode: '',
      versionCode: '',
      cfgLoading: false,
      cfgInfo: {},
      versionLoading: false,
      versionList: []
    }
  },
  computed: {
    rdcTypeList() {
      const list = this.dict?.type.cq_eval_rdc_type || []
      const rdcType = this.cfgInfo.rdcType || ''
      if (!rdcType || !list.length) return []

      const rdcTypes = rdcType.split(',').filter(i => i)
      return list.filter(i => rdcTypes.includes(i.value))
    },
    disableAction() {
      return !this.chkitemCode || !this.versionCode || this.listLoading || this.exportLoading || this.cfgLoading
    },
    showBtns() {
      // 操作按钮权限
      const permCode = this.$route.query.permCode
      const edit = auth.hasPermi(`cq:eval:${permCode}:edit`)
      const add = auth.hasPermi(`cq:eval:${permCode}:add`)
      const remove = auth.hasPermi(`cq:eval:${permCode}:remove`)
      const info = auth.hasPermi(`cq:eval:${permCode}:info`)
      // 有权解锁(启用)
      const enable = auth.hasPermi(`cq:eval:${permCode}:enable`)
      // 有权锁定(禁用)
      const disable = auth.hasPermi(`cq:eval:${permCode}:disable`)
      const isExport = auth.hasPermi(`cq:eval:${permCode}:export`)
      return { edit, add, remove, info, enable, disable, isExport }
    }
  },
  created() {
    treeselect().then(res => (this.deptOptions = res.data))
  },
  mounted() {
    this.initData()
  },
  methods: {
    normalizerDept(node) {
      // 转换检索部门数据结构
      if (!node.children?.length) delete node.children
      return { id: node.fid, label: node.label, children: node.children }
    },
    selectDept(node) {
      this.queryParams.projectName = ''
    },
    async initData() {
      const query = this.$route.query || {}
      const { versionCode, chkitemId, chkitemCode, rdcType } = query
      if (!versionCode) return this.msgError('参数错误：版本号不能为空')
      if (!chkitemId || !chkitemCode) return this.msgError('参数错误：检查项编码不能为空')
      this.versionCode = versionCode
      this.chkitemCode = chkitemCode
      this.hasRdcType = !!rdcType

      this.cfgInfo = { ...query }
      // await this.getVersionList()
      await this.getChildrenCfg()
      this.getList()
    },
    async getVersionList() {
      this.versionLoading = true
      const res = await listVersion({ isEnable: 1 }).catch(() => false)
      this.versionLoading = false
      if (res === false) return

      const data = res.data || []
      this.versionList = data
    },
    async getChildrenCfg() {
      const { versionCode, chkitemId } = this.cfgInfo
      if (!versionCode || !chkitemId) return

      const opt = { versionCode, parentId: chkitemId, isEnable: 1 }
      this.cfgLoading = true
      const res = await listChkitem(opt).catch(() => false)
      this.cfgLoading = false
      if (res === false) return

      const data = res.data || []
      await this.getEnumDicts(data)
      data.map(i => {
        i.chkitemCfgId = i.cfgId
      })
      // 排序
      data.sort((a, b) => {
        if (a.seq !== b.seq) return b.seq - a.seq
        return (a.chkitemCode || '').localeCompare(b.chkitemCode || '')
      })
      this.cfgInfo.children = data
    },
    async getEnumDicts(list) {
      // 获取枚举字典
      const enumList = list.filter(i => i.dataType === DATA_TYPE.ENUM)
      if (!enumList.length) return list

      const arr = enumList.map(i => i.scoreType)
      // 去重
      const dictNames = arr.filter((a, b) => arr.indexOf(a) === b)

      this.cfgLoading = true
      const res = await Promise.all(
        dictNames.map(dictName =>
          this.getDicts(dictName)
            .then(res => ({ [dictName]: (res.data || []).map(i => ({ label: i.dictLabel, value: i.dictValue, raw: i })) }))
            .catch(() => ({}))
        )
      ).catch(() => false)
      this.cfgLoading = false
      if (res === false) return list

      const data = res.reduce((o, i) => !void (o = { ...o, ...i }) && o, {})
      enumList.map(i => (i.enumDicts = data[i.scoreType] || []))
      return list
    },
    async getList() {
      const { showBtns } = this
      const opt = this.getQuery()
      if (!opt) return

      this.listLoading = true
      const res = await pageScorePrjchk(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.rows || []
      const deptName = i => [i.deptName1, i.deptName2, i.deptName3].filter(i => i).join(' - ')
      data.map(i => {
        i.showDeptName = deptName(i)
        i.removeLoading = false
        i.lockLoading = false
        i.isEditLock = i.isLockout ? showBtns.enable : showBtns.disable
      })

      this.list = data
      this.total = res.total || 0
    },
    getQuery() {
      const { versionCode, chkitemCode, dateRange } = this
      if (!chkitemCode) return void this.msgError('参数错误：检查项编码不能为空')
      if (!versionCode) return void this.msgError('请选择版本')

      const opt = { ...this.queryParams }
      opt.versionCode = versionCode
      opt.chkitemCode = chkitemCode
      if (!this.hasRdcType) opt.rdcType = ''
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        opt.startTime = dateRange[0]
        opt.endTime = dateRange[1]
      }
      return opt
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async handleDelete(item) {
      const res1 = await this.$confirm(`确认删除当前数据项: ${item.projectName}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await deletePrjchk(item.prjchkId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.list.length > 1 ? this.getList() : this.handleQuery()
    },
    async handleExport() {
      const { cfgInfo } = this
      if (!this.list.length) return this.msgInfo('暂无数据')
      const opt = this.getQuery()
      if (!opt) return
      // 不传分页参数
      delete opt.pageNum
      delete opt.pageSize

      const filename = `${cfgInfo.chkitemName || '检查项'}得分表`
      const res1 = await this.$confirm(`确定导出${filename}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.exportLoading = true
      const res = await exportReportPrjchk(opt).catch(() => false)
      this.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}_${new Date().Format('yyyyMMdd')}.xlsx`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    },
    async toggleLock(item) {
      if (item.lockLoading) return
      const isLockout = item.isLockout ? 0 : 1
      const name = isLockout === 1 ? '锁定' : '解锁'
      const res1 = await this.$confirm(`确认${name}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { prjchkId: item.prjchkId, isLockout }
      const submitApi = isLockout ? disableTaskPrjchk : enableTaskPrjchk
      item.lockLoading = true
      const res = await submitApi(opt).catch(() => false)
      item.lockLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    },
    openEditItem(item) {
      const { cfgInfo } = this
      this.$refs.EditItem.open(item, { cfgInfo })
    },
    openDetail(row) {
      const { cfgInfo } = this
      this.$refs.ChkitemScoreDetail.open({ cfgInfo, data: row })
    }
  }
}
</script>
<style lang="scss" scoped>
.tree-select-custom {
  width: 300px;
  /deep/ {
    .vue-treeselect__control {
      height: 28px;
      font-size: 12px;
    }
    .vue-treeselect__placeholder,
    .vue-treeselect__single-value {
      line-height: 26px;
    }
    .vue-treeselect__input-container,
    .vue-treeselect__input {
      height: 26px;
    }
  }
}
// 优化行 hover 时，检查项背景界限模糊
.table /deep/ .hover-row .cpn-score-display .item {
  background-color: white;
}
</style>
